package com.powernode.bank.service.impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
// @Transactional // 该类所有方法都采用事务
public class AccountServiceImpl implements AccountService {

    @Resource(name="accountDao")
    private AccountDao accountDao;

    // 控制事务
    @Transactional // 当前方法采用事务
    @Override
    public void transfer(String from, String to, Double money) {
        // 开启事务

        // 查询转出账户的余额是否充足
        Account fromAccount = accountDao.selectByActno(from);
        if(fromAccount.getBalance()<money){
            throw new RuntimeException("金额不足！！！");
        }
        Account toAccount = accountDao.selectByActno(to);

        // 将内存中两个对象的余额先修改
        fromAccount.setBalance(fromAccount.getBalance()-money);
        toAccount.setBalance(toAccount.getBalance()+money);

        // 数据库更新
        int count = accountDao.update(fromAccount);

        // 模拟事务
        /*String s=null;
        s.toString();*/

        count+=accountDao.update(toAccount);

        if(count!=2){
            throw new RuntimeException("转账失败，请联系银行！！！");
        }

        // 提交事务

        // 回滚事务
    }

    @Transactional(propagation= Propagation.REQUIRED)
    public void withdraw(){

    }

    @Resource(name = "accountService2")
    private AccountService accountService2;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void save(Account act) {
        // 调用dao的inset
        accountDao.insert(act); // 保存act-003账户

        Account act2=new Account("act-004",1000.0);
        try {
            accountService2.save(act2); // 保存账户act-004账户
        } catch (Exception e) {

        }
    }
}
